package mint2tcp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import javafx.application.Platform;
import java.io.IOException;

public class TcpClient implements Runnable {
    private String ip;
    private int port;
    private MainController controller;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private volatile boolean running = true;

    public TcpClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void setController(MainController controller) {
        this.controller = controller;
    }

    @Override
    public void run() {
        try {
            socket = new Socket(ip, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Platform.runLater(() -> {
                controller.setStatus("状态：已连接", "green");
                controller.appendResponse("Connected to server: " + ip + ":" + port + "\n");
            });

            while (running) {
                socket.setSoTimeout(1000);  // 1秒超时
                try {
                    String message = in.readLine();
                    if (message == null || !running) {
                        break;
                    }
                    controller.appendResponse(message + "\n");

                    DataParser.DataPoint dataPoint = DataParser.parseData(message);
                    Platform.runLater(() -> controller.addDataPoint(dataPoint));
                } catch (SocketTimeoutException e) {
                    if (!running) break;
                }
            }
        } catch (Exception e) {
            if (running) {
                Platform.runLater(() -> {
                    controller.setStatus("状态：连接失败", "red");
                    controller.appendResponse("Error: " + e.getMessage() + "\n");
                });
            }
        } finally {
            disconnect();
        }
    }

    public void disconnect() {
        running = false;
        try {
            if (in != null) in.close();
            if (out != null) out.close();
            if (socket != null && !socket.isClosed()) socket.close();
            
            Platform.runLater(() -> {
                controller.setStatus("状态：已断开", "red");
                controller.appendResponse("Disconnected from server\n");
            });
        } catch (Exception e) {
            Platform.runLater(() -> 
                controller.appendResponse("Error closing connection: " + e.getMessage() + "\n")
            );
        }
    }

    public void stop() {
        running = false;  // 首先设置running标志
        try {
            // 中断阻塞的读取操作
            if (socket != null) {
                socket.close();  // 这将强制中断 readLine()
            }
        } catch (IOException e) {
            Platform.runLater(() -> {
                controller.appendResponse("Error closing connection: " + e.getMessage() + "\n");
                controller.setStatus("状态：断开异常", "red");
            });
        }
    }
}